package name.sraynal.map.Sample;

// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import name.sraynal.map.BlankMap;

public class MyConnector {

	private static final Pattern LINK_PATTERN = Pattern
			.compile("[ ]*<a[ ]+href=\"([\\w.]+)\"[ ]*>(.*)</a><br>");
	private Map<String, String> urlLinks;
	private static final String URL_PREFIX = "http://geography.about.com/library/blank/";

	/**
	 * This program connects to a Web server and downloads the specified URL
	 * from it. It uses the HTTP protocol directly.
	 **/
	public void execute(String[] args) throws Exception {
		URL yahoo = new URL(URL_PREFIX + "blxindex.htm");
		URLConnection yc = yahoo.openConnection();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				yc.getInputStream()));
		this.urlLinks = new HashMap<String, String>();
		String inputLine;

		while ((inputLine = in.readLine()) != null) {
			Matcher linkMatcher = LINK_PATTERN.matcher(inputLine);

			if (linkMatcher.matches()) {
				this.urlLinks.put(linkMatcher.group(1), linkMatcher.group(2));
			}
		}
		in.close();

		getAllImages();

		System.out.println("GetBlankMap : done.");
	}

	private void getAllImages() throws IOException {
		Iterator<Entry<String, String>> it = this.urlLinks.entrySet()
				.iterator();

		while (it.hasNext()) {
			Entry<String, String> entry = it.next();

			System.out.println("GET " + entry.getValue() + ".jpg ...");
			BlankMap blankMap = new BlankMap(new URL(URL_PREFIX
					+ entry.getKey()), "c:\\temp\\maps", entry.getValue()
					+ ".jpg");
			blankMap.getFile();
			System.out.println("Done.");
		}
	}
}